package com.ljyh.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljyh.forum.entity.Category;
import com.ljyh.forum.mapper.CategoryMapper;
import com.ljyh.forum.service.CategoryService;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 分类服务实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getAllCategories() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        return this.list(queryWrapper);
    }

    @Override
    public boolean addCategory(String name) {
        // 检查分类名称是否已存在
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        if (this.getOne(queryWrapper) != null) {
            return false;
        }
        
        Category category = new Category();
        category.setName(name);
        return this.save(category);
    }

    @Override
    public boolean updateCategory(Integer id, String name) {
        // 检查分类是否存在
        Category category = this.getById(id);
        if (category == null) {
            return false;
        }
        
        // 检查新名称是否与其他分类冲突
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name).ne("id", id);
        if (this.getOne(queryWrapper) != null) {
            return false;
        }
        
        category.setName(name);
        return this.updateById(category);
    }

    @Override
    public boolean deleteCategory(Integer id) {
        // 检查分类是否存在
        Category category = this.getById(id);
        if (category == null) {
            return false;
        }
        
        // TODO: 检查该分类下是否有帖子，如果有则不能删除
        // 这里需要实现检查逻辑
        
        return this.removeById(id);
    }
}
